import {Button, Form, message, Modal, Radio, Tag} from 'antd';
import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {isSuccess, leftTime} from "@/utils/utils";
import {MobileDemandManager} from "@/services/api-functions";
import {SYS_ENUMS} from "@/utils/constants";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {history} from "@@/core/history";
import {ExclamationCircleOutlined} from "@ant-design/icons";
import {ModalForm, ProFormSelect, ProFormTextArea} from "@ant-design/pro-form";


export const demandAudit = async (fields: any, select: any, callBack?: Function) => {
  if (!select) return false;
  try {
    if (isSuccess((await MobileDemandManager.audit({
      businessId: select.id,
      auditOperate: fields.auditOperate,
      remark: fields.remark,
      flowType: 'DEMAND_AUDIT',
    }))?.code)) {
      message.success(fields.auditOperate === SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value ? '审核通过' : '审核拒绝');
      callBack?.();
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};

export const demandDelete = async (select: any) => {
  if (!select) return false;
  try {
    message.loading('正在删除');
    if (isSuccess((await MobileDemandManager.audit1(select.id))?.code)) {
      message.success('删除成功');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};


const DemandList: React.FC<any> = ({}) => {
  const [auditFormRef] = Form.useForm()
  const [auditState, setAuditState] = useState<'ALL' | 'AUDITING' | 'WAIT_ACCEPT' | 'DESIGNING' | 'WAIT_RECEIVE' | 'FINISH' | 'AUDIT_FAIL'>('AUDITING');
  const [countInfo, setCountInfo] = useState<{ ALL: number, AUDITING: number, WAIT_ACCEPT: number, DESIGNING: number, WAIT_RECEIVE: number, FINISH: number, AUDIT_FAIL: number }>({
    ALL: 0,
    AUDITING: 0,
    WAIT_ACCEPT: 0,
    DESIGNING: 0,
    WAIT_RECEIVE: 0,
    FINISH: 0,
    AUDIT_FAIL: 0,
  });
  const [auditVisible, handleAuditVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<any>();
  const columns: ProColumns[] = [
    {
      title: '标题',
      dataIndex: 'title',
      ellipsis: true,
      fixed: 'left',
      width: 350,
    },
    {
      title: '用户名',
      dataIndex: 'nickName',
      ellipsis: true,
      hideInTable: true,
      width: 120,
    },
    {
      title: '接单设计师',
      dataIndex: 'designerNickName',
      ellipsis: true,
      hideInTable: true,
      width: 120,
    },
    {
      title: '交付日期',
      dataIndex: 'finishTimeRange',
      valueType: 'dateTimeRange',
      width: 170,
      hideInTable: true,
    },
    {
      title: '发布日期',
      dataIndex: 'createTimeRange',
      valueType: 'dateTimeRange',
      width: 170,
      hideInTable: true,
    },
    {
      title: '用户',
      dataIndex: ['userDto', 'nickName'],
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '需求状态',
      dataIndex: 'demandStatus',
      valueEnum: SYS_ENUMS.DEMAND_STATUS,
      width: 100,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '接单设计师',
      dataIndex: ['acceptDesigner', 'nickName'],
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '页数',
      dataIndex: 'pageSize',
      width: 80,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '预算',
      dataIndex: 'budget',
      width: 130,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '付款金额',
      dataIndex: 'depositAmount',
      width: 130,
      hideInForm: true,
      hideInSearch: true,
      render: (_, record) => 0 + (record.depositAmount ?? 0) + (record.finalAmount ?? 0)
    },
    {
      title: '浏览量',
      dataIndex: 'browseNum',
      ellipsis: true,
      hideInSearch: true,
      width: 100,
    },
    {
      title: '接单人数',
      dataIndex: 'acceptNum',
      ellipsis: true,
      hideInSearch: true,
      width: 100,
    },
    {
      title: '剩余时间',
      dataIndex: 'draftTime',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
      render: (_, record) => leftTime(record.draftTime, false)
    },
    {
      title: '交付日期',
      dataIndex: 'finishTime',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '发布日期',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      fixed: 'right',
      width: 270,
      hideInForm: true,
      render: (_, record) => [
        <a key="edit"
           onClick={() => Modal.confirm({
             title: '提示',
             icon: <ExclamationCircleOutlined/>,
             content: <span>确定要删除 <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
             okText: '删除',
             cancelText: '取消',
             onOk: async () => {
               if (await demandDelete(record)) {
                 actionRef.current?.reload()
               }
             },
           })}
        >删除</a>,
        <a key="edit" href={`/custom/demand/detail/${record?.id}`}>详情</a>,
        (
          record.demandStatus === 'AUDITING'
            ? <a key="edit" onClick={() => {
              setCurrentRow(record)
              auditFormRef?.resetFields()
              handleAuditVisible(true)
            }}>审核</a> : <span style={{color: 'gray'}}>审核</span>
        ),<a key="edit" href={`/custom/demand/detail/${record?.id}`}>详情</a>,
        (
          record.depositOrderId
            ? <a key="edit" href={`/order/demand/list?id=${record.depositOrderId}`}>订单</a> : <span style={{color: 'gray'}}>订单</span>
        ),
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<any, any>
        headerTitle={<Radio.Group value={auditState} onChange={(e) => {
          setAuditState(e.target.value)
          actionRef.current?.reload()
        }}>
          <Radio.Button value='ALL'>全部 {countInfo?.ALL ?? 0}</Radio.Button>
          <Radio.Button value='AUDITING'>待审核 {countInfo?.AUDITING ?? 0}</Radio.Button>
          <Radio.Button value='WAIT_ACCEPT'>等待接单 {countInfo?.WAIT_ACCEPT ?? 0}</Radio.Button>
          <Radio.Button value='DESIGNING'>设计中 {countInfo?.DESIGNING ?? 0}</Radio.Button>
          <Radio.Button value='WAIT_RECEIVE'>待收货 {countInfo?.WAIT_RECEIVE ?? 0}</Radio.Button>
          <Radio.Button value='FINISH'>交易完成 {countInfo?.FINISH ?? 0}</Radio.Button>
          <Radio.Button value='AUDIT_FAIL'>未通过 {countInfo?.AUDIT_FAIL ?? 0}</Radio.Button>
        </Radio.Group>}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button onClick={() => history.push('/article/comments')}>订单列表</Button>,
        ]}
        request={async (params) => {

          const query = {...params}
          if (auditState !== 'ALL') {
            query.demandStatus = auditState
          }

          if (params.finishTimeRange) {
            query.finishStartTime = params.finishTimeRange[0]
            query.finishEndTime = params.finishTimeRange[1]
            delete query.finishTimeRange
          }
          if (params.createTimeRange) {
            query.createStartTime = params.createTimeRange[0]
            query.createEndTime = params.createTimeRange[1]
            delete query.createTimeRange
          }

          const {data: {data, total}, code}: any = await MobileDemandManager.list(query);

          const res = await MobileDemandManager.countInfo();

          if (isSuccess(res.code)) {
            setCountInfo(res.data)
          }

          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
        }}
        columns={columns}
        scroll={{ x: 1300 }}
      />

      <ModalForm
        title={`审核【${currentRow?.title}】`}
        width="750px"
        form={auditFormRef}
        visible={auditVisible}
        onVisibleChange={v => {
          handleAuditVisible(v)
          if (!v) {
            auditFormRef?.resetFields()
          }
        }}
        onFinish={async (value) => {
          // @ts-ignore
          if (await demandAudit(value as any, currentRow)) {
            handleAuditVisible(false);
            auditFormRef?.resetFields()
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect label='审核结果' required rules={[{required: true, message: '请填选择审核结果',},]} name='auditOperate'
                       initialValue={SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value} options={[
          {label: SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.label, value: SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value},
          {label: SYS_ENUMS.RESOURCE_AUDIT_STATE.REFUSE.label, value: SYS_ENUMS.RESOURCE_AUDIT_STATE.REFUSE.value},
        ]}/>
        <ProFormTextArea label='备注' name="remark"/>
      </ModalForm>
    </PageContainer>
  );
};

export default DemandList;
